#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    this->setWindowTitle("客户端");
    // 创建实例
    socket = new QTcpSocket(this);
    // 和服务器连接
    socket->connectToHost("127.0.0.1", 8000);
    // 连接信号，处理响应
    connect(socket, &QTcpSocket::readyRead, this, [=]{
        QString response = socket->readAll();
        ui->listWidget->addItem("服务端：" + response);
    });
    // 等待建立连接的结果
    bool ret = socket->waitForConnected();
    if (!ret)
    {
        QMessageBox::critical(this, "连接出错", socket->errorString());
        exit(1);
    }
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    // 读取输入框内容
    const QString& text = ui->lineEdit->text();
    // 发送给服务端
    socket->write(text.toUtf8());
    // 发的消息显示界面
    ui->listWidget->addItem("客户端：" + text);
    // 清空输入框
    ui->lineEdit->setText("");
}
